﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SGLisp;

namespace SGLib.AITree
{
    class AISyncNode : AINode
    {

        public AISyncNode(AITree tree)
        {
            mTree = tree;
        }
        public override void Load(ListNode astNode)
        {
            this.mNodeState = AINodeState.Wait;
            this.mNodeType = AINodeType.Sync;
            this.mChildrens = new List<AINode>();
            foreach (ListNode elemNode in astNode.nodes)
            {
                AINode curAINode = this.mTree.ParseNode(elemNode);
                this.mChildrens.Add(curAINode);
            }
        }

        public override void OnEnter(Context context)
        {
            this.mNodeState = AINodeState.Run;
            for (int i = 0; i < this.mChildrens.Count; i++)
            {
                this.mChildrens[i].OnEnter(context);
            }
        }

        public override void Update(Context context, float dt)
        {
            if (this.mNodeState == AINodeState.Wait)
            {
                return;
            }
            int FinishNumber = 0;
            for (int i = 0; i < this.mChildrens.Count; i++)
            {
                AINode curNode = this.mChildrens[i];
                if (curNode.NodeState == AINodeState.Run)
                {
                    curNode.Update(context, dt);
                }
                else if (curNode.NodeState == AINodeState.Finish)
                {
                    FinishNumber++;
                }
            }
            if (FinishNumber == this.mChildrens.Count)
            {
                this.mNodeState = AINodeState.Finish;
                for (int i = 0; i < this.mChildrens.Count; i++)
                {
                    this.mChildrens[i].OnExit();
                }
            }
        }
    }
}
